package com.ylkj.common.page;

import java.io.Serializable;

public class PageRequest implements Pageable, Serializable {
	private static final long serialVersionUID = -3352419269873108001L;

	private final int page;
	private final int size;

	public PageRequest(int page, int size)
	{
		if (page < 0)
			throw new IllegalArgumentException("Page index must not be less than zero!");
		if (size < 1)
		{
			throw new IllegalArgumentException("Page size must not be less than one!");
		} else
		{
			this.page = page;
			this.size = size;
			return;
		}
	}

	public int getPageSize()
	{
		return size;
	}

	public int getPageNumber()
	{
		return page;
	}

	public int getOffset()
	{
		return page * size;
	}

	public boolean hasPrevious()
	{
		return page > 0;
	}

	public Pageable next()
	{
		return new PageRequest(page + 1, size);
	}

	public Pageable previousOrFirst()
	{
		if (hasPrevious())
			return new PageRequest(page - 1, size);
		else
			return this;
	}

	public Pageable first()
	{
		return new PageRequest(0, size);
	}

	public boolean equals(Object obj)
	{
		if (this == obj)
			return true;
		if (getClass() != obj.getClass())
		{
			return false;
		} else
		{
			PageRequest that = (PageRequest)obj;
			boolean pageEqual = page == that.page;
			boolean sizeEqual = size == that.size;
			return pageEqual && sizeEqual;
		}
	}

	public int hashCode()
	{
		int result = 17;
		result = 31 * result + page;
		result = 31 * result + size;
		return result;
	}

	public String toString()
	{
		return String.format("Page request [number: %d, size %d]", new Object[] {
			Integer.valueOf(page), Integer.valueOf(size)
		});
	}
}
